﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FSAPI
{
    public class Client
    {
        private Ice.Communicator SendCommunicator = null;
        private Ice.Communicator RecvCommunicator = null;

        private string mainIpAddress;
        private string  ipAddress;
        private int port1;
        private int port2;
        private InspectionCallBackPrx InspectionCallBackProxy;//从机通过InspectionCallBackPrx向主机返回信息

        public InspectionCallBackDisp InspectionCallBack;

        public InspectionPrx InspectionProxy;//主机通过InspectionPrx控制从机执行操作
        public string ID { get; set; }
        public string Name { get; set; }
        public string Desc { get; set; }
        public string RelativePartID { get; set; }
        public enum ErrorType
        {
            OK=0,
            ConnectError =1,
        }
        public Client(string mainIP,string ip, int Port1, int Port2)
        {
            mainIpAddress = mainIP;
            ipAddress = ip;
            port1 = Port1;
            port2 = Port2;
            ID = string.Format("{0}_{1}", ip, Port1);
            this.RelativePartID = "";
        }

        public Client(string mainIP, string ip, int Port1, int Port2, string RelativePartID)
        {
            mainIpAddress = mainIP;
            ipAddress = ip;
            port1 = Port1;
            port2 = Port2;
            ID = RelativePartID;
            this.RelativePartID = RelativePartID;
        }

        public ErrorType Connect()
        {
            Ice.Properties properties = Ice.Util.createProperties();
            properties.setProperty("Ice.MessageSizeMax", "200000000");
            properties.setProperty("Ice.ThreadPool.Server.Size", "2");
            //properties.setProperty("Ice.ThreadPool.Client.Size", "2");
            //properties.setProperty("Ice.UDP.SndSize", "200000000");
            //properties.setProperty(" Ice.UDP.RcvSize", "200000000");
            Ice.InitializationData initData = new Ice.InitializationData();
            initData.properties = properties;
            SendCommunicator = Ice.Util.initialize(initData);
            Ice.ObjectPrx obj;
            obj = SendCommunicator.stringToProxy("RemoteServerInspection:default -h " + ipAddress + " -p " + port1.ToString());
            try
            {
                InspectionProxy = InspectionPrxHelper.checkedCast(obj);
            }
            catch (Exception ex)
            {
                BpjbCommon.Net.Core.BpEventHandler.ErrHandler(string.Format("从机连接失败：\n {0}！", ex.InnerException), BpjbCommon.Net.Core.ErrType.Warning);
                InspectionProxy = null;
            }
            if (InspectionProxy == null)
            {
                return ErrorType.ConnectError;
                //throw new ApplicationException("Invalid proxy");
            }

            RecvCommunicator = Ice.Util.initialize(initData);
            Ice.ObjectPrx obj3 = RecvCommunicator.stringToProxy("inspectioncallback:tcp -h " + mainIpAddress + " -p " + port2.ToString() + ":udp -h " + mainIpAddress + " -p " + port2.ToString());
            //InspectionCallBackProxy = InspectionCallBackPrxHelper.uncheckedCast(obj3.ice_datagram().ice_secure(false));
            InspectionCallBackProxy = InspectionCallBackPrxHelper.uncheckedCast(obj3);
            if (InspectionCallBackProxy == null)
            {
                throw new ApplicationException("Invalid proxy");
            }
            InspectionProxy.initiateCallback(InspectionCallBackProxy);
            InspectionCallBack = new InspectionCallBackDisp();
            Task task = new Task(() =>
                {
                    Ice.Communicator communtor_RecFromServer = Ice.Util.initialize(initData);
                    try
                    { 
                        Ice.ObjectAdapter adpter = communtor_RecFromServer.createObjectAdapterWithEndpoints("callback", string.Format("tcp -h {0} -p {1}:udp -h {0} -p {1}", mainIpAddress, port2.ToString())); //communtor.createObjectAdapter("Printer");//3.创建适配器对象，参数为(适配器名称，缺省TCP/IP,端口号)

                        adpter.add(InspectionCallBack, Ice.Util.stringToIdentity("inspectioncallback"));//5.在适配器中传入对象，以及适配器名称。（接受者可能有多个）
                        adpter.activate();//激活适配器，适配器创建完毕之后处于holding
                        communtor_RecFromServer.waitForShutdown();
                    }
                    catch (Exception ex)
                    {
                        throw new System.Exception(ex.Message);
                    }
                    try
                    {
                        communtor_RecFromServer.destroy();
                    }
                    catch (Ice.Exception ex)
                    {
                        throw new System.Exception(ex.Message);
                    }
                });
            task.Start();
            return ErrorType.OK;
        }

        public void Destroy()
        {
            if(SendCommunicator != null)
            {
                SendCommunicator.destroy();
            }

            if(RecvCommunicator != null)
            {
                RecvCommunicator.destroy();
            }
        }


         
    }
}
